import React, { Component } from "react";
import { Upload, message, Button, Input } from "antd";
import {
  LoadingOutlined,
  PlusOutlined,
  UploadOutlined,
} from "@ant-design/icons";
import "./upload.less";
const { TextArea } = Input;
class UploadUtil extends Component {
  constructor(props) {
    super(props);
    this.state = {
      fileList1: [], //图片
      fileList2: [], //笔记
      uploading: false,
      value: "",
    };
  }
  onChange = ({ target: { value } }) => {
    this.setState({ value });
  };
  handleUpload = () => {
    const { fileList1, fileList2 } = this.state;
    const formData = new FormData();
    fileList1.forEach((file, index) => {
      // this.transformFile(file).then(res=>{
      //     console.log(res)
      // }).catch(err=>{
      //     console.log(err)
      // })
      formData.append(`img`, file);
    });
    fileList2.forEach((file, index) => {
      formData.append(`md`, file);
    });
    formData.append('description',this.state.value)
    this.setState({
      uploading: false,
    });
    this.props
      .Submit(formData)
      .then((res) => {
        this.setState(
          {
            uploading: false,
            fileList1: [],
            fileList2: [],
            value: "",
          },
          function () {
          }
        );
        message.success("上传成功");
      })
      .catch((err) => {
        this.setState({
          uploading: false,
        });
        message.error("上传失败");
      });
  };
  render() {
    const { uploading, fileList1, fileList2 } = this.state;
    const props1 = {
      onRemove: (file) => {
        this.setState((state) => {
          const index = state.fileList1.indexOf(file);
          const newFileList = state.fileList1.slice();
          newFileList.splice(index, 1);
          return {
            fileList1: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        let reg = /[(jpg)(png)]/ig
        let result = reg.test(file.name.substring(file.name.lastIndexOf('.')+1))
        if(result){
          this.setState((state) => ({
            fileList1: [...state.fileList1, file],
          }));
        }else{
          message.error('只能上传jpg,或者png格式文件')
        }
       
        return false;
      },
      fileList:fileList1,
      progress: {
        strokeColor: {
          "0%": "#108ee9",
          "100%": "#87d068",
        },
        strokeWidth: 3,
        format: (percent) => `${parseFloat(percent.toFixed(2))}%`,
      },
      //   transformFile(file) {
      //     return new Promise(resolve => {
      //       const reader = new FileReader();
      //       reader.readAsDataURL(file);
      //       reader.onload = () => {
      //         const canvas = document.createElement('canvas');
      //         const img = document.createElement('img');
      //         img.src = reader.result;
      //         img.onload = () => {
      //           const ctx = canvas.getContext('2d');
      //           ctx.drawImage(img, 0, 0);
      //           ctx.fillStyle = 'red';
      //           ctx.textBaseline = 'middle';
      //           ctx.fillText('Ant Design', 20, 20);
      //           canvas.toBlob(resolve);
      //         };
      //       };
      //     });
      //   },
    };
    const props2 = {
      onRemove: (file) => {
        this.setState((state) => {
          const index = state.fileList2.indexOf(file);
          const newFileList = state.fileList2.slice();
          newFileList.splice(index, 1);
          return {
            fileList2: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        if(file.name.substring(file.name.lastIndexOf('.')+1) === 'md'){
          this.setState((state) => ({
            fileList2: [...state.fileList2, file],
          }));
        }else{
          message.error('只能上传md格式文件')
        }
        return false;
      },
      fileList:fileList2,
      progress: {
        strokeColor: {
          "0%": "#108ee9",
          "100%": "#87d068",
        },
        strokeWidth: 3,
        format: (percent) => `${parseFloat(percent.toFixed(2))}%`,
      },
    };
    return (
      <div className="upcontent">
        <h2
          style={{
            color: "#f99",
            fontSize: "20px",
            marginLeft: "20px",
            fontWeight: "bolder",
            marginBottom:'20px'
          }}
        >
          上传笔记>>
        </h2>
        <div className="up_container">
          <div className="fir">
            <span>1. 图片：</span>
          </div>
          <div className="las">
            <Upload {...props1}>
              <Button>
                <UploadOutlined /> 选择图片
              </Button>
            </Upload>
          </div>
          <div className="fir">
            <span>2.笔记描述</span>
          </div>
          <div className="las">
            <TextArea
              value={this.state.value}
              onChange={this.onChange}
              placeholder="Controlled autosize"
              autoSize={{ minRows: 3, maxRows: 5 }}
            />
          </div>
          <div className="fir">
            <span>3. 文件</span>
          </div>
         
          <div className="las">
            <Upload {...props2}>
              <Button>
                <UploadOutlined /> 选择文件
              </Button>
            </Upload>
            <Button
              type="primary"
              onClick={this.handleUpload}
              disabled={fileList1.length === 0 || fileList2.length === 0}
              loading={uploading}
              style={{ marginTop: 16 }}
            >
              {uploading ? "上传中" : "开始上传"}
            </Button>
          </div>
        </div>
      </div>
    );
  }
}
export default UploadUtil;
